package co.fitstart.admin.web.controller.user.student;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;

import co.fitstart.admin.service.CourseRoundService;
import co.fitstart.admin.service.StudentService;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.entity.course.CourseType;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.StudentTargetData;
import co.fitstart.entity.user.bwh.BwhRecord;
import co.fitstart.entity.user.inbody.InbodyRecord;
import co.fitstart.entity.user.investigation.FitInvestigation;
import co.fitstart.entity.user.investigation.HealthInvestigation;
import co.fitstart.entity.user.investigation.ParticipateInvestigation;

/**
 * 
 * @author lidan
 *
 */
@Controller
@RequestMapping("/{type}-students")
public class StudentViewController {
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @Autowired
    private StudentService studentService;
    
    @Autowired
    private CourseRoundService courseRoundService;
    
    private Logger logger = LoggerFactory.getLogger(StudentViewController.class);
    
    /**
     * 
     * @param type
     * @param studentId
     * @return
     */
    @RequestMapping(value="/{studentId}/body", method=RequestMethod.GET)
    public ModelAndView body(@PathVariable("type") String type,
                             @PathVariable("studentId") Long studentId) {
        
        ModelAndView modelAndView = new ModelAndView("student/view/student-body-view");
        modelAndView.addObject("type", type);
        
        Student student = studentService.load(Student.class, studentId);
        // 1. list userFitRecord by student`s user
        List<FitInvestigation> fitInvestigations = studentService.listFitInvestigation(student.getUser());
        modelAndView.addObject("fitInvestigations", fitInvestigations);
        
        // 2. list inbodyRecords by student's user
        List<InbodyRecord> inbodyRecords = studentService.listInbodyRecord(student.getUser());
        modelAndView.addObject("inbodyRecords", inbodyRecords);
        
        // 3. list bwhRecords by student's user
        List<BwhRecord> bwhRecords = studentService.listBwhRecord(student.getUser());
        modelAndView.addObject("bwhRecords", bwhRecords);
        
        // 4. list studentTargetDatas by student's user
        List<StudentTargetData> studentTargetDatas = studentService.listStudentTargetData(student.getUser());
        modelAndView.addObject("studentTargetDatas", studentTargetDatas);
        
        modelAndView.addObject("student", student);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param type
     * @param studentId
     * @return
     */
    @RequestMapping(value="/{studentId}/course", method=RequestMethod.GET)
    public ModelAndView course(@PathVariable("type") String type,
                               @PathVariable("studentId") Long studentId) {
        
        ModelAndView modelAndView = new ModelAndView("student/view/student-course-view");
        modelAndView.addObject("type", type);
        
        Student student = studentService.load(Student.class, studentId);
        List<CourseRound> courseRounds = courseRoundService.listCourseRound(student, StringUtils.equals(type, "online") ? new CourseType[]{CourseType.ONLINE} : new CourseType[]{CourseType.INDIVIDUAL, CourseType.SPECIAL, CourseType.POSTURE, CourseType.GROUP, CourseType.YEAR});
        modelAndView.addObject("courseRounds", courseRounds);
        
        modelAndView.addObject("student", student);
        
        return modelAndView;
    }
    
    /**
     * Display student BMI info page
     * 
     * @param type
     * @param studentId
     * @return
     */
    @RequestMapping(value="/{studentId}/bmi", method=RequestMethod.GET)
    public ModelAndView bmi(@PathVariable("type") String type,
                            @PathVariable("studentId") Long studentId) {
        
        ModelAndView modelAndView = new ModelAndView("student/view/student-bmi-view");
        modelAndView.addObject("type", type);
        
        Student student = studentService.load(Student.class, studentId);
        // 1. list userFitRecord by student`s user
        List<FitInvestigation> fitInvestigations = studentService.listFitInvestigation(student.getUser());
        modelAndView.addObject("fitInvestigations", fitInvestigations);
        
        // 2. list inbodyRecords by student's user
        List<InbodyRecord> inbodyRecords = studentService.listInbodyRecord(student.getUser());
        
        modelAndView.addObject("inbodyRecords", inbodyRecords);
        modelAndView.addObject("student", student);
        
        return modelAndView;
    }
    
    /**
     * Display student investigation info page
     * 
     * @param type
     * @param studentId
     * @return
     */
    @RequestMapping(value="/{studentId}/investigation", method=RequestMethod.GET)
    public ModelAndView investigation(@PathVariable("type") String type,
                                      @PathVariable("studentId") Long studentId) {
        ModelAndView modelAndView = new ModelAndView("student/view/student-investigation-view");
        modelAndView.addObject("type", type);
        
        Student student = studentService.load(Student.class, studentId);
        
        // 1. load healthInvestigation by student
        HealthInvestigation healthInvestigation = studentService.loadHealthInvestigation(student.getUser());
        modelAndView.addObject("healthInvestigation", healthInvestigation);
        
        // 2. load participateInvestigation by student
        ParticipateInvestigation participateInvestigation = studentService.loadParticipateInvestigation(student.getUser());
        modelAndView.addObject("participateInvestigation", participateInvestigation);
        
        modelAndView.addObject("student", student);
        
        return modelAndView;
    }
    
    /**
     * Display input info page
     * 
     * @param studentId
     * @return
     */
    @RequestMapping(value = "/{studentId}/input-info", method = RequestMethod.GET)
    public ModelAndView inputInfo(@PathVariable("type") String type, @PathVariable("studentId") Long studentId){
        
        ModelAndView modelAndView = new ModelAndView("student/view/student-input-info-view");
        
        Student student = studentService.load(Student.class, studentId);
        
        // 1. load healthInvestigation by student
        HealthInvestigation healthInvestigation = studentService.loadHealthInvestigation(student.getUser());
        modelAndView.addObject("healthInvestigation", healthInvestigation);
        
        // 2. load participateInvestigation by student
        ParticipateInvestigation participateInvestigation = studentService.loadParticipateInvestigation(student.getUser());
        modelAndView.addObject("participateInvestigation", participateInvestigation);
        
        modelAndView.addObject("user",student.getUser());
        
        modelAndView.addObject("student", student);
        modelAndView.addObject("type", type);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param studentId
     * @return
     */
    @RequestMapping(value="/{studentId}/name" , method = RequestMethod.GET)
    public ModelAndView editName(@PathVariable("studentId") Long studentId,
                                 @PathVariable("type") String type){
        
        ModelAndView modelAndView = new ModelAndView("student/view/student-name-edit");
        
        Student student = studentService.load(Student.class, studentId);
        
        modelAndView.addObject("student",student);
        modelAndView.addObject("type", type);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param student
     * @return
     */
    @RequestMapping(value = "/{studentId}/name" , method = RequestMethod.PATCH)
    public @ResponseBody String onEditName(@Preloading("studentId") Student student){
        
        Result result = new Result();
        
        try {
            
            studentService.editName(student);
            
            result.success().message("修改用户姓名成功");
            
        } catch (Exception e) {
            
            logger.error("#onEditName " , e);
            
            result.fail().message("修改用户姓名失败");
                    
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param bwhId
     * @return
     */
    @RequestMapping(value="/{studentId}/bwh", method=RequestMethod.GET)
    public ModelAndView editBwh(@RequestParam(name = "bwhId", required = false) Long bwhId, 
                                @PathVariable("type") String type,
                                @PathVariable("studentId") String studentId) {
        ModelAndView modelAndView = new ModelAndView("student/view/student-bwh-edit");
        
        if(bwhId != null) {
            modelAndView.addObject("bwh", genericDaoSupport.load(BwhRecord.class, bwhId));
        }
        
        modelAndView.addObject("type", type);
        modelAndView.addObject("studentId", studentId);
        modelAndView.addObject("bwhId", bwhId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param operator
     * @param bwhRecord
     * @return
     */
    @RequestMapping(value="/{studentId}/bwh", method=RequestMethod.PATCH)
    public @ResponseBody String onEditBwh(@Secure(property = "id") Long operator,
                                          @PathVariable("studentId") Long studentId,
                                          @RequestParam(name = "bwhId", required = false) Long bwhId,
                                          BwhRecord bwhRecord) {
        Result result = new Result();
        
        try {
            if(bwhId != null) {
                BwhRecord oldBwhRecord = genericDaoSupport.load(BwhRecord.class, bwhId);

                if(oldBwhRecord != null) {
                    studentService.editBwhRecord(oldBwhRecord.opeator(bwhRecord.getBust(), bwhRecord.getWaist(), bwhRecord.getHips(), operator));
                }
            } else {
                if(studentId != null) {
                    Student student = genericDaoSupport.load(Student.class, studentId);
                    if(student != null && student.getUser() != null) {
                        studentService.createBwhRecord(bwhRecord.initilization(student.getUser(), genericDaoSupport.load(Principal.class, operator)));
                    }
                }
            }
            
            result.success().message("三围数据补录成功");
        } catch (Exception e) {
            
            logger.error("onEditBwh() error: " , e);
            
            result.fail().message("三围数据补录失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param targetId
     * @return
     */
    @RequestMapping(value = "/target/{targetId}/edit", method = RequestMethod.GET)
    public ModelAndView editTarget(@PathVariable("type") String type,
                                   @PathVariable("targetId") Long targetId) {
        ModelAndView modelAndView = new ModelAndView("student/view/student-target-data-edit");

        StudentTargetData studentTargetData = genericDaoSupport.load(StudentTargetData.class, targetId);
        
        modelAndView.addObject("studentTargetData", studentTargetData);
        modelAndView.addObject("type", type);

        return modelAndView;
    }

    /**
     * 
     * @param operator
     * @param targetId
     * @param shortTarget
     * @param longTarget
     * @return
     */
    @RequestMapping(value = "/target/{targetId}/edit", method = RequestMethod.PATCH)
    public @ResponseBody String onEditTarget(@Secure(property = "id") Long operator,
                                             @PathVariable("targetId") Long targetId,
                                             @RequestParam("shortTarget") String shortTarget,
                                             @RequestParam("longTarget") String longTarget) {
        Result result = new Result();

        try {
            StudentTargetData target = genericDaoSupport.load(StudentTargetData.class, targetId);
            
            studentService.editTarget(target.edit(shortTarget, longTarget, operator));

            result.success().message("目标数据修改成功");

        } catch (Exception e) {

            logger.error("onEditUserTarget() error: ", e);

            result.fail().message("目标数据修改失败");
        }

        return JsonUtils.toJsonString(result);
    }
}
